import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import { useUserStore } from "./user";
import { insertCartAPI, getCartAPI, delCartAPI, changeStatusAPI, changeStatusAllAPI, updateCartAPI } from "@/api/cart";

export const useCartStore = defineStore(
  "cart",
  () => {
    const userStore = useUserStore();
    const isLogin = computed(() => userStore.userInfo.token);
    const cartList = ref([]);
    /*
    {
      id: goods.value.id ,//商品id
      name: goods.value.name, //商品名称
      price: goods.value.price, //商品价格
      picture: goods.value.mainPictures[0], //商品图片
      skuId: skuObj.skuId, //skuId
      count: num.value,
      attrsText: skuObj.specsText,//规格信息
      selected: true //商品是否被选择
    }
    */
    const getCartList = async () => {
      const res = await getCartAPI();
      cartList.value = res.result;
      console.log(cartList.value);
    };

    const addCart = async (goods) => {
      if (isLogin.value) {
        const { skuId, count } = goods;
        await insertCartAPI({ skuId, count });
        //console.log(res);
        getCartList();
       
      } else {
        const findResult = cartList.value.find(
          (item) => item.skuId === goods.skuId
        );
        if (!findResult) {
          cartList.value.push(goods);
        } else {
          //findResult.count += goods.count;
          findResult.count ++
        }
      }

      ElMessage.success("加入购物车成功");
    };

    const delCart = (skuId) => {
      //TODO: 删除商品数量
      // 找到要删除的索引
      const idx = cartList.value.findIndex((item) => item.skuId === skuId);
      // 如果找不到，直接返回
      if (idx === -1) return;
      // 如果找到了，删除一个
      cartList.value[idx].count--;
      // 如果删除后，数量为0，删除这个对象
      if (cartList.value[idx].count === 0) cartList.value.splice(idx, 1);
    };

    const delCartItem = async (skuId) => {
      // 找到要删除的索引
      if (isLogin.value) {
        await delCartAPI([skuId]);
        getCartList();
      } else {
        const idx = cartList.value.findIndex((item) => item.skuId === skuId);
        cartList.value.splice(idx, 1);
      }
    };

    const isAllChecked = computed(() => {
      return cartList.value.every((item) => item.selected);
    });

    const checkAll =async (selected) => {
      await changeStatusAllAPI(selected)
      getCartList()
      //cartList.value.forEach((item) => (item.selected = selected));
    };//

    const singleChange =async (selected, id) => {
      //console.log(selected, id);
      
      await changeStatusAPI(id,selected)
      getCartList()
      // const item = cartList.value.find((item) => item.skuId === id);
      // item.selected = selected;
    };//

    const selectedCount = computed(() => {
      return cartList.value
        .filter((item) => item.selected)
        .reduce((a, b) => a + b.count, 0);
    });

    const totalPrice = computed(() => {
      return cartList.value
        .filter((item) => item.selected)
        .reduce((a, b) => a + b.count * b.price, 0);
    });

    const clearCart = () => {
      cartList.value = [];
    };

    const updateCart = async(skuId,count) =>{
      await updateCartAPI(skuId,count)
      getCartList()
    }

    const getSelectedCartIds = computed(() => {
      return cartList.value.filter((item) => item.selected).map((item) => item.id);
    });
    return {
      cartList,
      addCart,
      delCart,
      delCartItem,
      isAllChecked,
      checkAll,
      selectedCount,
      totalPrice,
      singleChange,
      clearCart,
     getCartList,
     updateCart,
     getSelectedCartIds
    };
  },
  {
    persist: true,
  }
);
